const config = require('../../config');
const fetch = require('node-fetch');

export default class HuanxinService {
  private static async getAdminToken() {
    const url = `${config.huanxin.url}/token`;
    const data = {
      grant_type: 'client_credentials',
      client_id: config.huanxin.clientId,
      client_secret: config.huanxin.clientSecret
    };
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    });
    if (response.status !== 200 && response.status !== 304) {
      throw new Error('Bad Response.');
    }
    const token = await response.json();
    return token['access_token'];
  }
  public static async sendSystemMessage(receiveHxUserName, content) {
    const token = await this.getAdminToken();
    const url = `${config.huanxin.url}/messages`;
    const data = {
      target_type: 'users',
      target: [receiveHxUserName],
      msg: {
        type: 'txt',
        msg: JSON.stringify({
          sender: {hxUserName: 'admin'},
          text: content
        })
      },
      ext: {
        time: new Date()
      }
    };
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + token
      },
      body: JSON.stringify(data)
    });
    if (response.status !== 200 && response.status !== 304) {
      throw new Error('Bad Response.');
    }
    return true;
  }

  public static async sendRoomCmdMessage(hxRoomIdTo, cmdType, data, sender = {}) {
    const token = await this.getAdminToken();
    const url = `${config.huanxin.url}/messages`;
    const body = {
      target_type: 'chatrooms',
      target: [hxRoomIdTo],
      msg: {
        type: 'cmd',
        action: cmdType
      },
      ext: {
        sender,
        data,
        time: new Date()
      },
      from: hxRoomIdTo + 1
    };
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + token
      },
      body: JSON.stringify(body)
    });
    if (response.status !== 200 && response.status !== 304) {
      throw new Error('Bad Response.');
    }
    const result = await response.json();
    return result['data']['result'];
  }

  public static async sendChatroomMessage(hxRoomIdTo, text, sender) {
    const token = await this.getAdminToken();
    const url = `${config.huanxin.url}/messages`;
    const data = {
      target_type: 'chatrooms',
      target: [hxRoomIdTo],
      msg: {
        type: 'txt',
        msg: JSON.stringify({
          sender,
          text
        })
      },
      ext: {
        time: new Date()
      }
    };
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + token
      },
      body: JSON.stringify(data)
    });
    if (response.status !== 200 && response.status !== 304) {
      throw new Error('Bad Response.');
    }
    return true;
  }
}
